package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.model.mongo.Video;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@Slf4j
public class VideoService {

    //从调度服务器获取，一个目标存储服务器，上传
    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;// 获取存储服务器的请求URL

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    /**
     * 发布小视频
     * @param videoThumbnail
     * @param videoFile
     */
    public void publish(MultipartFile videoThumbnail, MultipartFile videoFile) {
        //1. 先上传视频文件到fastdfs上
        // 获取文件后缀名
        String filename = videoFile.getOriginalFilename();
        //不加1得到的是.mp4,我们不需要.，所以要+1
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        try {
            StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffix, null);
            // 视频的完整路径
            String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
            //2. 上传封面图片到oss上
            String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
            //3. 构建pojo
            Video pojo = new Video();
            pojo.setUserId(UserHolder.getUserId());
            pojo.setVideoUrl(videoUrl);
            pojo.setPicUrl(picUrl);
            pojo.setText("黑马出品");
            //4. 调用api保存
            videoApi.add(pojo);
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("上传小视频失败",e);
        }
    }
}
